package cn.lzx.service.impl;

import cn.lzx.domain.JsonResult;
import cn.lzx.domain.MovieTicket;

import cn.lzx.dto.UserMovieDto;
import cn.lzx.mapper.MovieTicketMapper;
import cn.lzx.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MovieServiceImpl implements MovieService {
    @Autowired
    private MovieTicketMapper movieTicketMapper;

    @Override
    public MovieTicket findById(Long id) {
        return movieTicketMapper.findById(id);
    }

    @Override
    public UserMovieDto getTicket(Long userId) {
        UserMovieDto ticket = movieTicketMapper.getTicket(userId);
        return ticket;
    }

    @Override
    public void buyTicket(UserMovieDto userMovieDto) {
        //根据id先获取电影票信息
        MovieTicket movie = movieTicketMapper.findById(userMovieDto.getMovieTicketId());
        //得到电影票数
        Integer stock = movie.getStock();
        //需要购买的票数
        Integer count = userMovieDto.getCount();
        //电影票剩余的票数
        int i = stock - count;
        if (i <0 || stock==0 ){//电影票为0或剩余票数小于0
            throw new RuntimeException("购买电影票失败");
        }
        //更新电影票数
        movie.setStock(i);
        movieTicketMapper.update(movie);

        //添加用户和电影票
        movieTicketMapper.addUserMovie(userMovieDto);


    }

}
